function showAlert(message) {
  document.getElementById('alertMessage').textContent = message;
  document.getElementById('customAlert').style.display = 'block';
  document.getElementById('alertMask').style.display = 'block';
}

function closeAlert() {
  document.getElementById('customAlert').style.display = 'none';
  document.getElementById('alertMask').style.display = 'none';
  var audio = document.getElementById("alarm");
  audio.pause();
}




get_msg = function () {
  fetch('/query_msg', {
    method: 'GET',
  })
    .then(response => response.json())
    .then(data => {
      if (data.parmcode == 1) {
        for (var i = 0; i < data.msgs.length; i++) {

          // data.msgs[i].time = data.msgs[i].time.split(".")[0];
          data.msgs[i].time = String(data.msgs[i].time).match(/[^:]*:[^:]*/);
          if (data.msgs[i].username == "system") {
            const regex = /<image:(.*?)>/;
            filename = data.msgs[i].message.match(regex)
            data.msgs[i].message = data.msgs[i].message.replace(/<image:[^>]+>/g, '');
            message_ok = data.msgs[i].message.replace(/\r?\n/g, '<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
            if (filename) {
              filename = filename[1]
              document.getElementById('messages').innerHTML += `
                              <div class="notification-item" style="color:var(--notification-item-system-text-color);">
                                  ${data.msgs[i].username}:${message_ok}
                                  <span class="timestamp">${data.msgs[i].time}</span>
                                  <br>
                                  <img src="/picture?filename=${filename}" alt="图片无法加载" style="max-width: 55%;">
                                  </div>`;
            } else {
              document.getElementById('messages').innerHTML += `
            <div class="notification-item" style="color:var(--notification-item-system-text-color);">
                ${data.msgs[i].username}:${data.msgs[i].message}
                <span class="timestamp">${data.msgs[i].time}</span>
                </div>`;
            }
          } else {
            document.getElementById('messages').innerHTML += `
                              <div class="notification-item" style="color:var(--notification-item-user-text-color);">
                                  ${data.msgs[i].username}:${data.msgs[i].message}
                                  <span class="timestamp">${data.msgs[i].time}</span>
                                  </div>`;
          }
        }
      } else {
        alert("获取失败，请重试")
      }
      var m = document.getElementById("messages");
      m.scrollTop = m.scrollHeight;
    });
}
function sendMessage() {
  const message = document.getElementById('message-input').value;
  if (message) {
    uname = document.getElementById("uname").innerText;
    console.log(uname)
    fetch('/send_msg', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: uname,
        message: message,
        time: new Date().toLocaleString() + "." + new Date().getMilliseconds()
      })
    })
      .then(response => response.json())
      .then(data => {
        if (data.parmcode == 1) {
          document.getElementById('message-input').value = '';
        } else {
          alert("发送失败，请重试")
        }
      });
  }
}
var message_form = document.getElementById("message_form")
message_form.addEventListener("submit", function (event) {
  event.preventDefault();
  sendMessage();
})


var host = window.location.host
const socket = new WebSocket("wss://" + host + "/ws_receive_msg");
socket.onmessage = function (event) {
  const message = event.data;
  var data = JSON.parse(message);

  data.time = String(data.time).match(/[^:]*:[^:]*/);
  if (data.username == "system") {
    const regex = /<image:(.*?)>/;
    filename = data.message.match(regex)
    data.message = data.message.replace(/<image:[^>]+>/g, '');
    message_ok = data.message.replace(/\r?\n/g, '<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
    if (filename) {
      filename = filename[1]
      document.getElementById('messages').innerHTML += `
      <div class="notification-item" style="color:var(--notification-item-system-text-color);">
        ${data.username}:${message_ok}
        <span class="timestamp">${data.time}</span>
        <br>
        <img src="/picture?filename=${filename}" alt="图片无法加载" style="max-width: 55%;">
        </div>`
    } else {
      document.getElementById('messages').innerHTML += `
    <div class="notification-item" style="color:var(--notification-item-system-text-color);">
      ${data.username}:${data.message}
      <span class="timestamp">${data.time}</span>
      </div>`


      // prosbtn=document.getElementById("prosBtn");
      // prosbtn.addEventListener('click', function () {
      //   console.log("prosBtn")
      //   window.location.replace("/audio");

      // })


    }
    var audio = document.getElementById("alarm");
    var m = document.getElementById("messages");//控制显示最新
    m.scrollTop = m.scrollHeight;//控制显示最新
    setTimeout(() => {

      audio.currentTime = 0;
      audio.play();
      showAlert(data.message);//弹出提示框
      // alert("时间：2025-12-12 12:12:12，系统消息：又有人微软")
    }, 0);

  } else {
    document.getElementById('messages').innerHTML += `
      <div class="notification-item" style="color:var(--notification-item-user-text-color);">
        ${data.username}:${data.message}
        <span class="timestamp">${data.time}</span>
        </div>`;
  }
  var m = document.getElementById("messages");
  m.scrollTop = m.scrollHeight;
};

socket.onerror = function (error) {
  const net_status = document.getElementById("net_status");
  net_status.innerHTML = "网络连接出错";
  net_status.style.backgroundColor = "crimson";

};
socket.onopen = function (event) {
  const net_status = document.getElementById("net_status");
  net_status.innerHTML = "网络已连接";
  net_status.style.backgroundColor = "#28a745";
};
socket.onclose = function (event) {
  const net_status = document.getElementById("net_status");
  net_status.innerHTML = "网络未连接";
  net_status.style.backgroundColor = "crimson";
};